using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin2022Soft2.Application.Common.Interface;
using Admin2022Soft2.Application.RequestDto;
using Admin2022Soft2.Application.ResponseDto;
using Admin2022Soft2.Application.Utils;
using Admin2022Soft2.Domain.Entity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Admin2022Soft2.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UsersController : ControllerBase
    {
        private readonly IRepository<AppUser> _appUser;
        private readonly IIdentityService _identityService;

        public UsersController(IRepository<AppUser> appUser, IIdentityService identityService)
        {
            _appUser = appUser;
            _identityService = identityService;
        }

        public async Task<AppUser> Post(CreateAppUserDto createAppUserDto)
        {
            // throw new Exception("我就是测试一下");
            var appUser = new AppUser
            {
                Username = createAppUserDto.Username,
                Password = createAppUserDto.Password
            };

            await _appUser.AddAsync(appUser);
            return appUser;
        }

        [AllowAnonymous]
        [HttpPost("/token")]
        public async Task<string> ValidateUser(UserForAuthDto userForAuthDto)
        {
            var token = await _identityService.ValidateUserAsync(userForAuthDto);

            if (token != null)
            {
                var res = new
                {
                    Code = 1000,
                    Data = token,
                    Msg = "登录成功"
                };
                return res.SerializeObject();
            }
            else
            {
                var res = new
                {
                    Code = 4000,
                    Data = token,
                    Msg = "用户名或者密码错误，请确认重试"
                };
                return res.SerializeObject();
            }
        }

        [AllowAnonymous]
        [HttpPost("/refresh")]
        public async Task<string> RefreshToken(AppTokenDto appTokenDto)
        {
            var token = await _identityService.RefreshTokenAsync(appTokenDto);
            if (token != null)
            {
                var res = new
                {
                    Code = 1000,
                    Data = token,
                    Msg = "登录成功"
                };
                return res.SerializeObject();
            }
            else
            {
                var res = new
                {
                    Code = 4000,
                    Data = token,
                    Msg = "用户名或者密码错误，请确认重试"
                };
                return res.SerializeObject();
            }
        }
    }
}